package cc.eddic.pratice.programmingparadigms.nginxlog;

import cc.eddic.pratice.programmingparadigms.advanced.BeanFactory;
import cc.eddic.pratice.programmingparadigms.nginxlog.impl.LogItemParserTyqImpl;
import cc.eddic.pratice.programmingparadigms.nginxlog.impl.NginxLogParserTyqImpl;
import lombok.val;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertNotNull;

public class NginxLogTestTyq {

    private static final Logger log = LoggerFactory.getLogger(NginxLogTestTyq.class);
    private final TextFileReader textFileReader = BeanFactory.getBean(TextFileReader.class, "");
    private final NginxLogParser nginxLogParser = BeanFactory.getBean(NginxLogParser.class, "");

    NginxLogParserTyqImpl nginxLogParserTyq = new NginxLogParserTyqImpl();

    private final LogItemParser logItemParser = new LogItemParserTyqImpl();

    @Test
    public void pvUv() throws IOException {
        val data = nginxLogItemStream().collect(Collectors.toList());
        val report = nginxLogParserTyq.pageViewsAndUniqueVisitors(data);
        assertNotNull(report);
    }

    private Stream<NginxLogItem> nginxLogItemStream() throws IOException {
        String fn = "D:\\SONY培训\\access.log\\access.log";
        if (log.isDebugEnabled()) log.debug("nginx log row count {}", textFileReader.read(fn).count());
        return textFileReader.read(fn).map(nginxLogParser::parse).filter(Optional::isPresent).map(Optional::get);
    }

    @Test
    public void pvUvByHour() throws IOException {
        val data = nginxLogItemStream().collect(Collectors.toList());
        val hourMap = nginxLogParserTyq.pageViewsAndUniqueVisitorsByHour(data);
        assertNotNull(hourMap);
        //输出hourMap
        for (Integer time : hourMap.keySet()) {
            System.out.println(time + ": " + hourMap.get(time));
        }
    }

    @Test
    public void pvUvByPath() throws IOException {
        val pathModelList = nginxLogParserTyq.pageViewsAndUniqueVisitorsByPath(logItemList());
        assertNotNull(pathModelList);
        //输出pathModelList
        for (LogReport.PathModel pathModel : pathModelList) {
            System.out.println(pathModel.getPath() + ": " + pathModel.getPv() + ": " + pathModel.getUv());
        }
    }

    private List<LogItem> logItemList() throws IOException {
        return nginxLogItemStream()
                .map(logItemParser::parse).filter(Optional::isPresent).map(Optional::get)
                .collect(Collectors.toList());
    }
}
